package web.servlet;

import domain.Account;
import domain.Log;
import domain.Product;
import service.LogService;
import service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "mainFormServlet", urlPatterns = {"/mainForm"})
public class MainFormServlet extends HttpServlet {
    private static final String MAIN_FORM = "/WEB-INF/jsp/catalog/Main.jsp";
    public static Map<String, String> spc = new HashMap<>();

    static {
        spc.put("cat", "猫类");
        spc.put("dog", "狗类");
        spc.put("fish", "鱼类");
        spc.put("bird", "鸟类");
        spc.put("hamster", "鼠类");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String species = spc.get(req.getParameter("species"));
        List<Product> products = new ProductService().searchProducts(species);
        for(Product product : products){
            product.setImageSize("mid");
        }
        req.setAttribute("productList", products);
        req.setAttribute("species", species);
        Account loginUser = (Account) req.getSession().getAttribute("loginUser");
        if(loginUser != null){
            new LogService().newLog(new Log(loginUser.getUserid(), "访问了-" + species + "-页面"));
        }
        req.getRequestDispatcher(MAIN_FORM).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

